﻿using System.Collections.Generic;
using System.IO;
using Red.Controls.ViewModels;
using Red.Core;

namespace Red.Controls.Depot.FileViewItemsProviders
{
    public class DirectoryFileViewItemsProvider : FileViewItemsProvider
    {
        #region Data

        private readonly bool _isReadOnly;
        private readonly List<string> _errors = new List<string>();

        #endregion Data

        #region C-tor

        public DirectoryFileViewItemsProvider( string path, DepotInfo depot, bool isReadOnly )
            : base( path, depot )
        {
            _isReadOnly = isReadOnly;
        }

        #endregion C-tor

        #region Properties

        public override IEnumerable<CommandWrapper> Commands
        {
            get 
            {
                var commands = new List<CommandWrapper>();
                commands.Add( new CommandWrapper( UICommands.CreateResource, Path ) );
                commands.Add( new CommandWrapper( UICommands.ImportResource, Path ) );
                commands.Add( new CommandWrapper( UICommands.CreateFolder, Path ) );
                commands.Add( new CommandWrapper( UICommands.CloseTab, Path ) );
                return commands;
            }
        }

        #endregion Properties

        #region Public methods

        public override void EnumerateItems( IList<FolderInfo> folders, IList<FileInfo> files, IList<FileInfo> selectedFiles )
        {
            var dirInfo = new DirectoryInfo( Path );
            EnumerateDirectories( dirInfo, folders );
            EnumerateFiles( dirInfo, files );
        }

        #endregion Public methods

        #region Private methods

        private void EnumerateDirectories( DirectoryInfo dirInfo, IList<FolderInfo> folders )
        {
            _errors.Clear();
            try
            {
                var directories = dirInfo.EnumerateDirectories();
                foreach ( var dir in directories )
                {
                    try
                    {
                        folders.Add( new FolderInfo{ Name = dir.Name, IsFake = false } );
                    }
                    catch ( System.UnauthorizedAccessException e )
                    {
                        _errors.Add( e.Message );
                    }
                }
            }
            catch ( IOException e )
            {
                _errors.Add( e.Message );
            }
            catch ( System.UnauthorizedAccessException e )
            {
                _errors.Add( e.Message );
            }
        }

        private void EnumerateFiles( DirectoryInfo dirInfo, IList<FileInfo> files )
        {
            var directoryFiles = dirInfo.EnumerateFiles();
            foreach ( var file in directoryFiles )
            {
                files.Add( new FileInfo() { FullPath = file.FullName, Group = "Files" } );
            }
        }

        #endregion Private methods
    }
}
